package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import beans.User;

import model.Model;
import model.UserDAO;

import formbeans.ChangePwdForm;

/*
 *  Course: S09-15437 - WEB APPLICATION DEVELOPMENT 
 * 	Name: Jiale Huang
 * 	Andrew ID: jialeh
 * 	Date: 2/23/2009
 *  Assignment: Hw4
 */


public class ChangePwdAction extends Action{

	private FormBeanFactory<ChangePwdForm> formBeanFactory = FormBeanFactory.getInstance(ChangePwdForm.class);
	
	private UserDAO userDAO;
	
	public ChangePwdAction(Model model){
		
		userDAO = model.getUserDAO();
	}
	
	@Override
	public String getName() {
		return "change-pwd.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        try {
            /*
        	// Set up user list for nav bar
			request.setAttribute("userList",userDAO.getUsers());
	        */
        	
	        // Load the form parameters into a form bean
	        ChangePwdForm form = formBeanFactory.create(request);
	        
	        // If no params were passed, return with no errors so that the form will be
	        // presented (we assume for the first time).
	        if (!form.isPresent()) {
	            return "changepwd.jsp";
	        }
	
	        // Check for any validation errors
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "changepwd.jsp";
	        }
	        
			User user = (User) request.getSession().getAttribute("user");
			
			if(user.checkPassword(form.getOldPassword())){
				// Change the password
	        	userDAO.setPassword(user, form.getNewPassword());
				request.setAttribute("message","Password changed for "+user.getUserEmail());
			}else{
				errors.add("Old password wrong!!!");
				return "changepwd.jsp";
			}
	        
			String webapp = request.getContextPath();
			return webapp + "/listBookmarks.do";			
        } catch (DAOException e) {
        	errors.add(e.toString());
        	return "change-pwd.jsp";
        } catch (FormBeanException e) {
        	errors.add(e.toString());
        	return "change-pwd.jsp";
        }
	}

}
